<?php
/**
 * Introduction: 全返汇总表  quanfan_count
 */

namespace Common\Model;


use Think\Model;

class QuanfanCountModel extends Model
{
    //定义数据库连接信息
    protected $connection;

    //定义表名
    protected $tableName = 'quanfan_count';

    /**
     * 初始化
     */
    public function _initialize()
    {

        $this->connection = C('Databaese');

    }

    /**
     * 获取数据
     */
    public function getOne($member_id){

        return $info = $this->where("member_id=$member_id")->field("returned_money,remained_money,order_total,return_total")->find();

    }

    /**
     * 更新统计信息
     * @param $memberId
     * @param $params
     * @param $isReturn
     * @return mixed
     */
    public function updateByUserId($memberId, $params, $isReturn = false){
        // 是否已经存在？
        $info = $this->getOne($memberId);

        if(!empty($info)){
            // 修改
            $data = array();

            if(!$isReturn){
                $data['order_total'] = $params['order_price'] + $info['order_total'];   // 总订单金额
                $data['return_total'] = $params['return_price'] + $info['return_total']; // 总应返金额
                $data['remained_money'] = $params['return_price'] + $info['remained_money']; // 总待返金额， 已返金额不变
            }else{
                // 系统返福利了...已返金额和待返金额都有变化...
                $data['returned_money'] = $info['returned_money'] + $params['returned_money'];  // 总已返金额
                $data['remained_money'] = $info['remained_money'] - $params['returned_money'];  // 总待返金额
            }

            $res = $this->where("member_id=$memberId")->save($data);
        }else{
            // 添加
            $data = array();
            $data['member_id'] = $memberId;
            $data['order_total'] = $params['order_price'];
            $data['return_total'] = $params['return_price'];
            $data['remained_money'] = $params['return_price'];
            $data['returned_money'] = 0;

            $data['return_total'] = ($data['return_total'] > 1000) ? 1000 : $data['return_total'];

            $res = $this->add($data);
        }

        return $res;
    }


}